window.addEventListener('DOMContentLoaded', () => {
  const tableBody = document.querySelector('#disk-table tbody');
  const refreshBtn = document.getElementById('refresh');
  const offlineBtn = document.getElementById('offline');
  const onlineBtn = document.getElementById('online');
  const onlineNoLetterBtn = document.getElementById('online-no-letter');
  const offlineExceptCjBtn = document.getElementById('offline-except-cj');
  const selectAll = document.getElementById('select-all');
  
  // 当前所有磁盘数据
  let currentDisks = [];

  async function loadDisks() {
    tableBody.innerHTML = '<tr><td colspan="7">加载中...</td></tr>';
    currentDisks = await window.diskAPI.getDisks();
    if (!currentDisks.length) {
      tableBody.innerHTML = '<tr><td colspan="7">未检测到磁盘</td></tr>';
      return;
    }
    
    // 按盘符升序排序（无盘符的排后）
    currentDisks.sort((a, b) => {
      if (!a.DriveLetters && !b.DriveLetters) return 0;
      if (!a.DriveLetters) return 1;
      if (!b.DriveLetters) return -1;
      return a.DriveLetters.localeCompare(b.DriveLetters);
    });
    
    tableBody.innerHTML = '';
    for (const d of currentDisks) {
      const sizeGB = d.Size ? (d.Size / 1024 / 1024 / 1024).toFixed(2) : '';
      tableBody.innerHTML += `
        <tr>
          <td><input type="checkbox" class="disk-check" value="${d.DeviceId}"></td>
          <td>${d.FriendlyName || ''}</td>
          <td>${d.DeviceId}</td>
          <td>${d.MediaType || ''}</td>
          <td>${d.OperationalStatus || ''}</td>
          <td>${sizeGB}</td>
          <td>${d.DriveLetters || ''}</td>
        </tr>
      `;
    }
  }

  refreshBtn.onclick = loadDisks;
  loadDisks();

  selectAll.onclick = () => {
    document.querySelectorAll('.disk-check').forEach(cb => {
      cb.checked = selectAll.checked;
    });
  };

  // 检查磁盘是否包含C或J盘符
  function hasCJDrive(driveLetters) {
    if (!driveLetters) return false;
    
    // 分割盘符字符串并检查每个盘符
    const letters = driveLetters.split(/,\s*/);
    return letters.some(letter => letter === 'C' || letter === 'J');
  }

  // 批量脱机操作
  offlineBtn.onclick = async () => {
    const checked = Array.from(document.querySelectorAll('.disk-check:checked'));
    if (!checked.length) return alert('请先选择要脱机的磁盘');
    const ids = checked.map(cb => cb.value);
    const ok = await window.diskAPI.offlineDisks(ids);
    if (ok) {
      alert('脱机操作成功！');
      loadDisks(); // 操作后自动刷新
    } else {
      alert('操作失败，请以管理员身份运行！');
      loadDisks(); // 失败也刷新
    }
  };
  
  // 批量联机操作
  onlineBtn.onclick = async () => {
    const checked = Array.from(document.querySelectorAll('.disk-check:checked'));
    if (!checked.length) return alert('请先选择要联机的磁盘');
    const ids = checked.map(cb => cb.value);
    const ok = await window.diskAPI.onlineDisks(ids);
    if (ok) {
      alert('联机操作成功！');
      loadDisks(); // 操作后自动刷新
    } else {
      alert('操作失败，请以管理员身份运行！');
      loadDisks(); // 失败也刷新
    }
  };
  
  // 联机所有无盘符磁盘
  onlineNoLetterBtn.onclick = async () => {
    // 过滤出无盘符的磁盘
    const noLetterDisks = currentDisks.filter(disk => !disk.DriveLetters || disk.DriveLetters.trim() === '');
    if (!noLetterDisks.length) return alert('未检测到无盘符磁盘！');
    
    const ids = noLetterDisks.map(disk => disk.DeviceId);
    const ok = await window.diskAPI.onlineDisks(ids);
    if (ok) {
      alert(`成功联机 ${ids.length} 个无盘符磁盘！`);
      loadDisks(); // 操作后自动刷新
    } else {
      alert('操作失败，请以管理员身份运行！');
      loadDisks(); // 失败也刷新
    }
  };
  
  // 除C/J盘外全部脱机
  offlineExceptCjBtn.onclick = async () => {
    // 过滤出不包含C和J盘符的磁盘
    const disksToOffline = currentDisks.filter(disk => !hasCJDrive(disk.DriveLetters));
    if (!disksToOffline.length) return alert('没有可脱机的磁盘(除C/J盘)！');
    
    if (!confirm(`确定要对 ${disksToOffline.length} 个磁盘执行脱机操作吗？(除C/J盘外所有磁盘)`)) return;
    
    const ids = disksToOffline.map(disk => disk.DeviceId);
    const ok = await window.diskAPI.offlineDisks(ids);
    if (ok) {
      alert(`成功脱机 ${ids.length} 个磁盘！(除C/J盘外所有磁盘)`);
      loadDisks(); // 操作后自动刷新
    } else {
      alert('操作失败，请以管理员身份运行！');
      loadDisks(); // 失败也刷新
    }
  };
});
